/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DBL;

import MDL.Produkt;
import java.sql.*;

/**
 *
 * @author Niklas
 */
public class DBProdukt implements IFDBProdukt
{

    Connection con = DBConnection.getInstance().getDBcon();

    public DBProdukt()
    {
    }

    public int createProdukt(Produkt produkt)
    {
     //   int vareId = GetMax.getNextID("SELECT MAX(vareId) FROM produkt");
     //   vareId++;

        int rc = -1;
        String query = "INSERT INTO produkt(vareId, varenavn, pris, note, antal) VALUES(" + produkt.getVareId() + ",'" + produkt.getVarenavn() + "'," + produkt.getPris() +",'" + produkt.getNote() + "'," + produkt.getAntal() + ")";

        System.out.println(query);
        try
        {
            Statement state = con.createStatement();
            state.setQueryTimeout(6);
            rc = state.executeUpdate(query);
            state.close();
        } catch (Exception e)
        {
            System.out.println("ERROR:" + e);
        }
        System.out.println(rc);
        return rc;
    }

    public int updateProdukt(Produkt pro)
    {
        int rc = -1;

        String query = "UPDATE produkt SET " +
                "samletAntal" + pro.getSamletAntal() + ",'" +
                "varenavn" + pro.getVarenavn() + "'," +
                "note ='" + pro.getNote() + ",'" +
                "pris'" + pro.getPris() + ")";


        System.out.println(query);
        try
        {
            Statement state = con.createStatement();
            state.setQueryTimeout(5);
            rc = state.executeUpdate(query);
            state.close();
        } catch (Exception e)
        {
            System.out.println("ERROR: " + e);
        }
        return rc;
    }

    public Produkt findProdukt(int vareId, Produkt pro)
    {
        int id = 0;
        ResultSet results;

        String query = "SELECT id, samletAntal, pris, note, varenavn FROM Produkt WHERE vareId = " + vareId;
        try
        {
            Statement state = con.createStatement();
            results = state.executeQuery(query);
            if (results.next())
            {
                pro.setVareId(results.getInt(1));
                pro.setPris(results.getFloat(2));
                pro.setSamletAntal(results.getInt(3));
                pro.setVarenavn(results.getString(4));
                pro.setNote(results.getString(5));

            }
            state.close();
        } catch (Exception e)
        {
            System.out.println("ERROR: " + e);
        }
        return pro;
    }

    public void deleteProdukt(int vareId)
    {
        String query = "DELETE FROM Produkt WHERE vareId = '" + vareId + "'";
        try
        {
            Statement state = con.createStatement();
            state.executeUpdate(query);
            state.close();
        } catch (Exception e)
        {
            System.out.println("ERROR: " + e);
        }
    }
}
